/**
*** 工具类
*** author:xieguojun
***
**/

Ext.namespace('Wssip.util');

/**
*** 将Ext.data.Record 转换成 Arrary
*** record:Ext.data.Record
*** key:record的主键
*** value:值
***/
Wssip.util.recordToArray =function(record,key,value){
	var result =[];
	
	result.push(record.get(key));
	result.push(record.get(value));
	
	return result;
}

/**
***  将Ext.data.Record 数组 转换成 Arrary 数组
***/
Wssip.util.recordsToArrays=function(records,key,value){
	
	if(!Ext.isArray(records)){
		return null;
	}
	
	var result =[];
	for(var i=0;i<records.length;++i){
		var r =records[i];
		
		var d =[];
		
		d.push(r.get(key));
		d.push(r.get(value));
		result.push(d);
	}
	return result;	
}

/**
*** 转化身份证，将15位或者18位的身份证转换为正确的18为身份证
**/
Wssip.util.idCardTo18 =function(idcard) {
	var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
	var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
	var sum = 0;
	 
	if(idcard.length != 15 &&idcard.length != 18) {
		return idcard;
	}

	if (idcard.length == 15) {
		idcard = idcard.substr(0, 6) + '19'+ idcard.substr(6, idcard.length - 6);
	} else {
		idcard = idcard.substr(0, 17);
	}

	for (var i = 0; i < idcard.length; i++) {
		sum += idcard.substr(i, 1) * arrInt[i];
	}

	idcard += arrCh[sum % 11];

	return idcard;
}

/**
**  校验身份证是否合法
**/	
Wssip.util.validateIdCard = function(value) {
	
	//huyunming注释
	//if(typeof value =='undefined' || !value || value ==''){
	//	return "身份证号码为空!";
	//}	

	//if (value.length != 15 && value.length != 18) {
	//	return '身份证号码长度应该为15位或者18位!';
	//}
	//huyunming注释
	
	
	if(value=='' || value==null){
		return true;
	}
	if (value.length != 18) {
		return '身份证号码长度应该为18位!';
	}
	
	var patten1 = "^\\d{15}$";
	var patten2 = "^\\d{17}[0123456789Xx]$";

	if (!new RegExp(patten1, "g").test(value)&& !new RegExp(patten2, "g").test(value)) {
		return '身份证号码只能包含数字和X';
	}
	
	var id18 = Wssip.util.idCardTo18(value);

	var csrqstr = id18.substr(6, 8);
	var year = parseInt(csrqstr.substr(0, 4), 10);
	var month = parseInt(csrqstr.substr(4, 2), 10) - 1;
	var date = parseInt(csrqstr.substr(6, 2), 10);
	
	var csrq = new Date(year, month, date);
	
	if (year != csrq.getFullYear() || month != csrq.getMonth()|| date != csrq.getDate()) {
		return '身份证中的出生日期['+csrqstr +']非法!';
	}

	//huyunming注释
	//if(value !=id18){
	//	return "身份证不正确，正确的身份证号码为:["+id18+"]";
	//}	
	//huyunming注释
	if(value !=id18){
		return "身份证不正确!";
	}
	
	return true; 
}

/**
*** 将身份证转换为 出生日期和性别
*** 返回：错误身份证返回空
*** 返回：正确身份证，返回数据，第一个为Date类型的生日，第二个为整形的性别(0:男,1:女)
**/
Wssip.util.idcardToDateAndSex =function(idcard){
	
	var id18 =Wssip.util.idCardTo18(idcard);
	
	var dateAndSex =[];
	
	if(Wssip.util.validateIdCard(id18) !==true){
		return dateAndSex;
	}
	
	var csrqstr = id18.substr(6, 8);
	var year = parseInt(csrqstr.substr(0, 4), 10);
	var month = parseInt(csrqstr.substr(4, 2), 10) - 1;
	var date = parseInt(csrqstr.substr(6, 2), 10);
	var csrq = new Date(year, month, date);
	
	dateAndSex[0] =csrq;
	
	var sexInt = parseInt(id18.substr(16, 1));
	
	if(sexInt % 2 ===0)
		dateAndSex[1] =2;
	else
		dateAndSex[1] =1;	 
		
	return dateAndSex;
	
}

/**
 * targetUrl:提交的action
 * params:附加参数
 * method:POST 或者GET
 * completeFunction：成功回调
 * failureFunction：失败回调
 * waitMsg:等待信息
 * timeout:超时设置 ms数
 */
Wssip.util.request = function(targetUrl, params, method, completeFunction,failureFunction,waitMsg,timeout,ingoreProgressTask) {
	if (waitMsg) {
		var percentage = 0;
		Ext.MessageBox.show({
			title : '\u8fdb\u5ea6\u6761',
			msg : waitMsg,
			progressText : 'Initializing...',
			width : 300,
			progress : true,
			closable : false
		});
		if(waitMsg){
			var progressTask = {
				run : function() {
					var progress = percentage / 100;
					if (progress >= 1) {
						progress = 1;
					}
					Ext.MessageBox.updateProgress(progress, (progress * 100) + "%");
					percentage = percentage + 10;
				},
				interval : 1000
					// 1 second
			}
			var taskRunner = new Ext.util.TaskRunner();
			taskRunner.start(progressTask);
		}
	}

	if (timeout) {
		Ext.Ajax.timeout = timeout;
	}else{
	    Ext.Ajax.timeout=10000000;
	}
	Ext.Ajax.request({
		url : targetUrl,
		params : (typeof(params) != 'undefined') ? params : {},
		method : (typeof(method) != 'undefined') ? method : 'post',
		waitMsg : (typeof(waitMsg) != undefined) ? waitMsg : 'Waiting...',
		isUpload :false,
		success : function(options,response) {
			
			if (waitMsg) {
				taskRunner.stop(progressTask);
				Ext.MessageBox.hide();
				percentage = 0;
			}
			
			var form ={}; 
			var json=null;
			
			json =Ext.decode(options.responseText);
			
			form.response=options;
			form.exception=json.exception;
			if(json.success){
				if(typeof completeFunction =='function'){
					completeFunction(options,form);
					}
				else
					Ext.Msg.alert('提示', '操作成功！');  	
			}else{
				if(typeof failureFunction =='function'){
					failureFunction(options,form);
				}
				else{
				    Ext.Msg.alert('错误',form.exception[0].msg);
					return false;	
				}
			}
		},
		failure:function(options,response){
			
			if (waitMsg) {
				taskRunner.stop(progressTask);
				Ext.MessageBox.hide();
				percentage = 0;
			} 
			
			var form ={}; 
			var json=null;
			
			if(options.status ==200){
				json =Ext.decode(options.responseText);
				form.response=options;
				form.exception=json.exception;
			}else{
				json={};
				json.success=false;
			}
			form.response=response;
			if(json.success){
				if(typeof completeFunction =='function')
					completeFunction(options,form);
				else
					Ext.Msg.alert('提示', '操作成功！');  	
			}else{
				if(typeof failureFunction =='function')
					failureFunction(options,form);
				else{
					Ext.Msg.alert('提示', '操作失败！'); 	
					}				
			}
		}
	});
}

/* **************************************************************** */
/*                   读卡器获取信息                                                                                          */
/* **************************************************************** */
/**
 * 读卡器获取信息，暂时只读取身份证（增强版）  
 * 		例：
 * 			var result = readDataFormMachineX("rd");
 * 			if(result.success){
 * 				var aac147 = result.aac147;
 * 			}else{
 * 				alert(result.msg);
 * 				return;
 * 			}
 * @param {Object} t10nId 控件标签ID
 * @return {TypeName} 返回json对象
 */
function readDataFormMachineX(t10nId){
	try{
		var num = initAndReadCardNumX(t10nId);
		return { success: true, aac147: num, cac002: null, msg: "读取成功！" };
	}catch(err){
		return { success: false, aac147: null, cac002: null, msg: err };
	}
}
/**
 * 读卡器获取信息（已弃用，请使用增强版!）     
 * 
 * @param {Object} cac002 社保电脑号标签ID
 * @param {Object} aac147 身份证号标签ID
 * @param pflag true: 遇到错误提示； false: 遇到错误不提示
 * @return {TypeName} 
 */
function readDataFormMachine(cac002, aac147, pflag){
	var flag = true;
	if(typeof(pflag) == "boolean"){
		flag = pflag;
	}
	var cac00200 = Ext.getCmp(cac002);
	var aac14700 = Ext.getCmp(aac147);
	var errorText = "";
	if(null == cac00200){
		errorText = "找不到id为【" + cac002 + "】的标签";
		Wonders.Msg.info(errorText);
		return false;
	}
	if(null == aac14700){
		errorText = "找不到id为【" + aac147 + "】的标签";
		Wonders.Msg.info(errorText);
		return false;
	}
	try{
	    if(!hasText(trim(cac00200.getValue())) 
	    		&& !hasText(trim(aac14700.getValue()))){
	    	var num = initAndReadCardNumX("rd");
	        Ext.getCmp(aac147).setValue(num);
	    }
	    return true;
	}catch(err){
		if(flag){
			alert(err);
		}
		return false;
	}
}
/**
 * 获取读卡器身份证号码
 * @return {TypeName} 
 */
function initAndReadCardNumX(t10nId){
	try{
    	var st = -1;
    	var number = null;
    	var rd = document.getElementById(t10nId);
    	if(null == rd){
    		throw "找不到控件标签【" + t10nId + "】！";
    	}
        st = rd.dc_init(100, 115200);
        if (st <= 0){ //返回值小于等于0表示失败
    		throw "初始化读卡器失败，请检查线路连接是否正确！";
        }
        rd.DC_find_i_d();
        st = rd.DC_start_i_d();
        if (st < 0){
    		throw "请把身份证放置到感应区域, 重新操作！";
        }
        st = rd.dc_beep(20);
        if (st < 0){
        	throw "设备蜂鸣异常！";
        }
        number = rd.DC_i_d_query_id_number();
        rd.DC_end_i_d();
        st = rd.dc_exit();
        if (st < 0) { //返回值小于0表示失败
        	throw "命令没有正确退出，请联系读卡器厂商！";
        }
        return number;
	}catch(err){
		throw err;
	}
}
/**
 * 判断字符串是否为空
 * @param {Object} source
 * @return {TypeName} 
 */
function hasText(source){
    if(typeof(source) == 'undefined' || null == source || source.length <= 0 ){
        return false;
    }else{
        return true;
    }
}
//去掉字符串头尾空格   
function trim(str) {   
    return str.replace(/(^\s*)|(\s*$)/g, "");   
}  
/* **************************************************************** */















